<template>
  <div class="city">
    <my-title title="城市列表" :fixed="true"></my-title>
    <!-- 索引栏 -->
    <van-index-bar :index-list="indexList" :sticky-offset-top="46" highlight-color="#21b97a">
      <van-index-anchor index="#">当前城市</van-index-anchor>
        <van-cell @click="$router.back()" :title="cityInfo.name" />

      <van-index-anchor index="热">热门城市</van-index-anchor>
        <van-cell @click="onAddressChange(item.label,item.value)" v-for="item in hotCityList" :key="item.label" :title="item.label" />

      <!-- 具体数据 -->
      <div v-for="item in cityList" :key="item.letter">
        <van-index-anchor :index="item.letter" />
        <van-cell @click="onAddressChange(item2.label,item2.value)" v-for="item2 in item.cityInfo" :key="item2.label" :title="item2.label" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import MyTitle from '@/components/MyTitle'
import { getCityList, getHotCityList } from '@/api/city.js'
export default {
  name: 'City',
  data () {
    return {
      indexList: ['#', '热'],
      cityList: [],
      hotCityList: []
    }
  },
  computed: {
    ...mapState(['cityInfo'])
  },
  components: {
    MyTitle
  },
  created () {
    this.getCityList()
    this.getHotCityList()
  },

  methods: {
    ...mapMutations(['getCityInfo']),
    // 点击更改地址
    onAddressChange (name, id) {
      this.getCityInfo({ name, id })
      this.$router.back()
    },
    async getHotCityList () { // 获取热门城市列表数据
      try {
        const res = await getHotCityList()
        this.hotCityList = res.data.body
      } catch (error) {
        console.log('获取热门城市列表数据失败')
      }
    },
    async getCityList () { // 获取城市列表数据
      try {
        const res = await getCityList(1)
        // console.log(res.data.body)
        this.handle(res.data.body)
      } catch (error) {
        console.log('获取城市列表数据失败')
      }
    },
    // 城市列表数据处理
    handle (arr) {
      const newArr = [...new Set(arr.map(item => item.short.split('')[0].toUpperCase()))].sort()
      // console.log(newArr)
      this.indexList.push(...newArr)
      newArr.forEach(item => this.cityList.push({
        letter: item,
        cityInfo: arr.filter(item2 => item2.short.split('')[0].toUpperCase() === item)
      }))
      console.log(this.cityList)
    }
  }
}
</script>

<style scoped lang='less'>
.van-index-bar{
  margin-top: 46px;
}
/deep/.van-index-anchor{
  color: #999;
}
/deep/.van-cell__title{
  font-size: 16px;
  color: #333;
}
/deep/.van-index-bar__sidebar{
  height: 85%;
  padding-top: 60px;
}
/deep/.van-index-bar__index{
  flex: 1;
  font-size: 14px;
  color: #333;
}
</style>
